﻿using FMStudio.Documents.DataDocument.Properties;
using FMStudio.Domain.SQLite;
using System;
using System.ComponentModel.Composition;
using System.IO;

namespace FMStudio.Documents.DataDocument
{
    [Export(typeof(IDocumentType)), Export]
    public class DataDocumentType : DocumentType<DataDocument>
    {
        public DataDocumentType()
            : base(Resources.DocumentDescription, Resources.DocumentExtension)
        {
        }


        #region Methods
        #region Public Methods
        public override bool CanNew() { return true; }

        public override bool CanOpen() { return true; }
        #endregion

        #region Protected Methods
        protected override DataDocument NewCore(string filePath)
        {
            if (!Directory.Exists(Path.GetDirectoryName(filePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(filePath));
            }
            File.WriteAllBytes(filePath, Resources.FMSData);

            return OpenCore(filePath);
        }

        protected override DataDocument OpenCore(string filePath)
        {
            DataDocument document = new DataDocument();
            document.FilePath = filePath;

            const string ConnectString = "metadata=res://*/FMStudioEntities.csdl|res://*/FMStudioEntities.ssdl|res://*/FMStudioEntities.msl;provider=System.Data.SQLite;provider connection string='data source=\"|DataFile|\";useutf16encoding=True'";

            string connectString = ConnectString.Replace("|DataFile|", filePath);
            FMStudioEntities entities = new FMStudioEntities(connectString);

            document.Entities = entities;

            return document;
        }

        protected override bool CanSaveCore() { return true; }

        protected override void SaveCore(DataDocument document, string filePath)
        {
            if (!CanSave(document))
            {
                throw new InvalidOperationException("You must not call Save when CanSave returns false.");
            }
            try
            {
                document.Entities.SaveChanges();
            }
            catch
            {
                throw;
            }
        }
        #endregion
        #endregion
    }
}
